
package com.kugou.game.sdk.ui.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.IEventCode;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.BasePayRequestParams;
import com.kugou.game.sdk.entity.Coupon;
import com.kugou.game.sdk.entity.KubiPayRequestParams;
import com.kugou.game.sdk.entity.PayConstant.ChargeType;
import com.kugou.game.sdk.entity.UnionPayRequestParams;
import com.kugou.game.sdk.interfaces.OnAliPayListener;
import com.kugou.game.sdk.interfaces.OnKubiPayListener;
import com.kugou.game.sdk.protocol.AliPayTask;
import com.kugou.game.sdk.protocol.AliPayTask.AliPayHttpResponse;
import com.kugou.game.sdk.protocol.CheckPayPasswdStateTask;
import com.kugou.game.sdk.protocol.CheckPayPasswdStateTask.CheckPayPswStateResponse;
import com.kugou.game.sdk.protocol.WeiXinPayTask;
import com.kugou.game.sdk.protocol.WeiXinPayTask.WeiXinPayHttpResponse;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.dialog.InputPayPasswdDialog;
import com.kugou.game.sdk.ui.dialog.InputPayPasswdDialog.OnPasswordChangedListener;
import com.kugou.game.sdk.ui.dialog.SelectOptionDialog;
import com.kugou.game.sdk.ui.dialog.SelectOptionDialog.OnSelectOptionListener;
import com.kugou.game.sdk.ui.fragment.RechargeByKuBiFragment;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;

/**
 * 描述:酷币不足的情况下支付界面
 *
 * @author wcj
 * @since 2014年12月10日 上午11:25:59
 */
public class NotEnoughKubiRechargeActivity extends BaseCommonTitleFragmentActivity {

    public static final String ORDER_VALUE = "order_value";

    public static final String ORDER_COUPON = "ORDER_COUPON";

    private static final int RECHARGE_TYPE_ALIPAY = 0;

    private static final int RECHARGE_TYPE_UNION = 1;

    private static final int RECHARGE_TYPE_WECHAT = 2;

    // 启动activity的请求码
    private final int CODE_START_ACTIVITY_REQUEST = 10000;

    // 请求支付
    private static final int MSG_REQUEST_ALIPAY = 1001;

    // 请求支付宝支付成功
    private final int MSG_ALIPAY_SUCCESS = 1002;

    // 请求支付宝支付失败
    private final int MSG_ALIPAY_FAILED = 1003;

    // 开始加载
    private final int MSG_START_LOADING = 1004;

    private final int MSG_REQUEST_UNION = 1005;

    private final int MSG_REQUEST_WECHAT = 1006;

    /**
     * 请求游币支付成功
     */
    private final int MSG_KUBIPAY_SUCCESS = 1009;

    /**
     * 请求游币支付失败
     */
    private final int MSG_KUBIPAY_FAILED = 1010;

    private final int MSG_REQUEST_KUBI_PAY = 1011;

    /**
     * 支付结束
     */
    private final int MSG_STOP_LOADING = 1012;

    private final int MSG_REQUEST_ALIPAY_INFO_SUCCESS = 1013;

    private final int MSG_REQUEST_ALIPAY_INFO_FAILED = 1014;

    private final int MSG_REQUEST_ALIPAY_INFO = 1015;

    private final int MSG_REQUEST_WEIXIN_INFO_SUCCESS = 1016;

    private final int MSG_REQUEST_WEIXIN_INFO_FAILED = 1017;

    private final int MSG_REQUEST_WEIXIN_PAY = 1018;

    private final int MSG_REQUEST_FAILED = 1019;

    // 请求支付密码状态
    private final int MSG_REQUEST_PAY_STATUS = 1020;

    private static final int MSG_REQUEST_PAY_STATUES_SUCCESS = 1021;

    private TextView mRechargeTypeTextView;

    private LinearLayout mRechargeSuccessLayout;

    private RelativeLayout mRechargeLayout;

    private ImageView mArrowImageView;

    private LoadingView mLoadingView;

    private int mRechargeType = 0;

    private int mRechargeValue = 0;

    private Coupon mSelectedCoupon;

    /**
     * 支付订单号
     */
    private String mOrderId;

    private InputPayPasswdDialog mInputPayPasswdDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        int layoutId = 0;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            layoutId = Rx.layout.kg_activity_not_enough_kubi_recharge_land;
        } else {
            layoutId = Rx.layout.kg_activity_not_enough_kubi_recharge;
        }
        setContentView(layoutId);

        mRechargeValue = getIntent().getIntExtra(ORDER_VALUE, 0);
        mSelectedCoupon = (Coupon) getIntent().getSerializableExtra(ORDER_COUPON);

        initViews();
    }

    private void initViews() {
        setCommonTitle("游戏充值");

        mLoadingView = (LoadingView) findViewById(Rx.id.kg_loadingView);

        TextView userNameTextView = (TextView) findViewById(Rx.id.kg_account_info);
        userNameTextView.setText(Html.fromHtml("<font color=#ff666666>当前账号：</font>"
                + "<font color=#fd9526>" + UserManager.getInstance().getCurrentUserName()
                + "</font>"));

        TextView orderTextView = (TextView) findViewById(Rx.id.kg_kubi_info);
        int rechargeValue = mRechargeValue
                - (mSelectedCoupon != null ? mSelectedCoupon.getMoney() : 0);
        orderTextView.setText(Html.fromHtml("<font color=#666666>支付金额：</font>"
                + "<font color=#fd9526>" + rechargeValue + "</font>元<font color=#666666>"
                + (mSelectedCoupon != null ? "（已计算代金券减免）" : "") + "</font>"));

        TextView orderTextView2 = (TextView) findViewById(Rx.id.kg_order_info);
        orderTextView2.setText("支付" + mRechargeValue + "元");

        TextView gameTextView = (TextView) findViewById(Rx.id.kg_game_info);
        gameTextView.setText("<" + AppUtil.getAppName(this) + ">" + "游戏订单");

        TextView kubiRemainTextView = (TextView) findViewById(Rx.id.kg_kubi_remain_value);

        kubiRemainTextView.setText("游币余额："
                + UserManager.getInstance().getCurrentUserInternal().getKubiNum() + "游币");

        TextView kubiRechargeTextView = (TextView) findViewById(Rx.id.kg_kubi_recharge_value);
        kubiRechargeTextView.setText(Html.fromHtml("<font color=#666666>支付</font>"
                + "<font color=#fd9526>"
                + UserManager.getInstance().getCurrentUserInternal().getKubiNum() + "</font>"
                + "<font color=#666666>游币</font>"));
        if (UserManager.getInstance().getCurrentUserInternal().getKubiNum() <= 0) {
            kubiRechargeTextView.setVisibility(View.GONE);
        }

        TextView otherRechargeValueTextView = (TextView) findViewById(Rx.id.kg_other_recharge_value);
        otherRechargeValueTextView.setText(Html.fromHtml("<font color=#666666>支付</font>"
                + "<font color=#fd9526>" + calcNeedMoney() + "</font>"
                + "<font color=#666666>元</font>"));

        mRechargeLayout = (RelativeLayout) findViewById(Rx.id.kg_recharge_info_layout);
        mArrowImageView = (ImageView) findViewById(Rx.id.kg_more_info_arrow);
        RelativeLayout gameInfoLayout = (RelativeLayout) findViewById(Rx.id.kg_game_info_layout);
        gameInfoLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mRechargeLayout.getVisibility() == View.VISIBLE) {
                    mRechargeLayout.setVisibility(View.GONE);
                    mArrowImageView.setImageResource(Rx.drawable.kg_account_select);

                } else {
                    mRechargeLayout.setVisibility(View.VISIBLE);
                    mArrowImageView.setImageResource(Rx.drawable.kg_account_unselect);
                }
            }
        });

        mRechargeTypeTextView = (TextView) findViewById(Rx.id.kg_kubi_recharge_type);
        mRechargeTypeTextView.setText(Html.fromHtml("<font color=#666666>其他支付方式：</font>"
                + "<font color=#249EF6>支付宝</font>"));
        mRechargeTypeTextView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showRechargeTypeDialog();
            }
        });

        Button summitButton = (Button) findViewById(Rx.id.kg_btn_summit);
        summitButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                summitRecharge();
            }
        });

        Button finishBtn = (Button) findViewById(Rx.id.kg_btn_back_to_game);
        finishBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                enterGame();
                finish();
            }
        });

        mRechargeSuccessLayout = (LinearLayout) findViewById(Rx.id.kg_layout_recharge_success);

    }

    private void enterGame() {
        // 回到游戏
        Intent intent = new Intent(SDKActions.ACTION_BACK_TO_GAME);
        sendBroadcast(intent);
    }

    private void showRechargeSuccessView() {
        hideLoadingView();

        Intent intent = new Intent();
        setResult(RechargeByKuBiFragment.NO_KUBI_RECHARGE_RESPONDE_CODE, intent);
        finish();
    }

    private void summitRecharge() {
        if (mRechargeType == RECHARGE_TYPE_ALIPAY) {
            sendEmptyBackgroundMessage(MSG_REQUEST_ALIPAY);
        } else if (mRechargeType == RECHARGE_TYPE_UNION) {
            sendEmptyBackgroundMessage(MSG_REQUEST_UNION);
        } else if (mRechargeType == RECHARGE_TYPE_WECHAT) {
            sendEmptyBackgroundMessage(MSG_REQUEST_WECHAT);
        }
    }

    private void showRechargeTypeDialog() {
        SelectOptionDialog dialog = new SelectOptionDialog(this);
        ArrayList<String> options = new ArrayList<String>();

        dialog.setCurrentOptionIndex(mRechargeType);
        dialog.setDialogTitle("请选择支付方式");

        options.add("支付宝");
        options.add("银行卡");
        options.add("微信");

        dialog.addDatas(options);

        dialog.setOnSelectOptionListener(new OnSelectOptionListener() {

            @Override
            public void afterSelectUser(String option, int index) {

                mRechargeType = index;
                mRechargeTypeTextView.setText(Html.fromHtml("<font color=#666666>其他支付方式：</font>"
                        + "<font color=#249EF6>" + option + "</font>"));
            }
        });
        dialog.show();
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        switch (msg.what) {
            case MSG_REQUEST_ALIPAY:
                sendEmptyUiMessage(MSG_START_LOADING);
                payByAlipay();
                break;

            case MSG_REQUEST_UNION:
                sendEmptyUiMessage(MSG_START_LOADING);
                payByUnion("");
                break;

            case MSG_REQUEST_WECHAT:
                sendEmptyUiMessage(MSG_START_LOADING);
                payByWeixin();
                break;

            case MSG_REQUEST_PAY_STATUS:
                sendEmptyUiMessage(MSG_START_LOADING);
                checkPayPasswdState();
                break;

            case MSG_REQUEST_KUBI_PAY:

                payByKubi(msg.obj != null ? (String) msg.obj : "");
                break;

            case MSG_REQUEST_ALIPAY_INFO:
                if (msg.obj != null) {
                    PayManager.payByAli(this, (String) msg.obj, onAliPayListener);
                }
                break;
            case MSG_REQUEST_WEIXIN_PAY:
                if (msg != null && msg.obj != null) {
                    WeiXinPayHttpResponse response = (WeiXinPayHttpResponse) msg.obj;
                    double money = Double.parseDouble(calcNeedMoney() + "");
                    String tokenid = response.getResult_tokenid();
                    String orderid = response.getResult_orderid();
                    PayManager.payByWeixin(this, money, tokenid, orderid);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        if (isFinishing()) {
            return;
        }
        Message message;

        switch (msg.what) {
            case MSG_START_LOADING:
                hideSoftInput(this);
                showLoadingView();
                break;
            case MSG_STOP_LOADING:
                hideLoadingView();
                break;
            case MSG_ALIPAY_SUCCESS:
                sendEmptyBackgroundMessage(MSG_REQUEST_PAY_STATUS);
                break;
            case MSG_ALIPAY_FAILED:
                hideLoadingView();
                Bundle bundle = msg.getData();
                if (bundle != null) {
                    String errorMsg = bundle.getString("errorMsg");
                    if (!TextUtils.isEmpty(errorMsg)) {
                        showNoticeDialog(errorMsg);
                    }
                }
                break;
            case MSG_REQUEST_ALIPAY_INFO_FAILED:
                String errorMsg = (String) msg.obj;
                if (!TextUtils.isEmpty(errorMsg)) {
                    showNoticeDialog(errorMsg);
                }
                hideLoadingView();
                break;
            case MSG_REQUEST_ALIPAY_INFO_SUCCESS:
                message = Message.obtain();
                message.what = MSG_REQUEST_ALIPAY_INFO;
                message.obj = msg.obj;
                sendBackgroundMessage(message);
                break;

            case MSG_KUBIPAY_SUCCESS:
                Bundle chargeData = new Bundle();
                chargeData.putString("orderid", mOrderId);
                chargeData.putInt("optype", 2);
                chargeData.putInt("paytype", mRechargeType);
                chargeData.putInt("paymoney", mRechargeValue);
                PlatformEventDispatcher.sendEvent(IEventCode.RECHARGE_SUCCESS, chargeData);

                // 更新内存的游币余额数量
                UserManager.getInstance().updateYoubiNum();
                showRechargeSuccessView();
                break;
            case MSG_KUBIPAY_FAILED:
                hideLoadingView();
                if (msg.obj != null && !TextUtils.isEmpty(msg.obj.toString())) {
                    showNoticeDialog(msg.obj.toString());
                }
                break;

            case MSG_REQUEST_WEIXIN_INFO_FAILED:
                if (msg.obj != null) {
                    errorMsg = (String) msg.obj;
                    if (!TextUtils.isEmpty(errorMsg)) {
                        showNoticeDialog(errorMsg);
                    }
                }
                hideLoadingView();
                break;
            case MSG_REQUEST_WEIXIN_INFO_SUCCESS:
                message = Message.obtain();
                message.what = MSG_REQUEST_WEIXIN_PAY;
                message.obj = msg.obj;
                sendBackgroundMessage(message);
                break;
            case MSG_REQUEST_FAILED:
                if (msg.obj != null) {
                    errorMsg = (String) msg.obj;
                    if (!TextUtils.isEmpty(errorMsg)) {
                        showNoticeDialog(errorMsg);
                    }
                }
                hideLoadingView();
                break;

            case MSG_REQUEST_PAY_STATUES_SUCCESS:
                hideLoadingView();
                showInputPayPasswdDialog();
                break;

            default:
                break;
        }
    }

    private void showLoadingView() {
        mLoadingView.setText("充值中，请稍候!");
        mLoadingView.setVisibility(View.VISIBLE);
    }

    private void hideLoadingView() {
        mLoadingView.setVisibility(View.GONE);
    }

    /**
     * 显示一些消息提示的确定弹框
     * 
     * @param tips 弹框Message
     */
    private void showNoticeDialog(String tips) {
        final BaseConfirmDialog failedDialog = new BaseConfirmDialog(this);
        failedDialog
                .setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
        failedDialog.setMessage(TextUtils.isEmpty(tips) ? "" : tips);
        failedDialog.setCancelBtnVisibility(View.GONE);
        failedDialog.setContentGravity(Gravity.CENTER);
        failedDialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                failedDialog.dismiss();

            }
        });
        failedDialog.show();
    }

    /**
     * 支付宝支付请求
     */
    private void payByAlipay() {
        int payValue = calcNeedMoney();

        BasePayRequestParams requestParams = new BasePayRequestParams();
        mOrderId = SDKControler.createNewOrderId();
        User user = UserManager.getInstance().getCurrentUserInternal();
        requestParams.setUserName(user.getAccountName());
        requestParams.setChargeType(ChargeType.TYPE_ALIPAY);
        requestParams.setMoney(payValue * 100);
        requestParams.setDirectCharge(0);
        requestParams.setOutOrderId(mOrderId);
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());

        AliPayTask httpTask = new AliPayTask();
        AliPayHttpResponse response = httpTask.request(requestParams);
        Message msg = Message.obtain();
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                if ("0".equals(response.getResult_code())
                        && !TextUtils.isEmpty(response.getResult_msg())) {
                    String info = response.getResult_msg();
                    msg.what = MSG_REQUEST_ALIPAY_INFO_SUCCESS;
                    msg.obj = info;
                } else {
                    msg.what = MSG_REQUEST_ALIPAY_INFO_FAILED;
                    msg.obj = response.getResult_msg();
                }
            } else {
                msg.what = MSG_REQUEST_ALIPAY_INFO_FAILED;
                msg.obj = response.getPrompt();
            }
        } else {
            msg.what = MSG_REQUEST_ALIPAY_INFO_FAILED;
            msg.obj = "网络异常，请检查网络连接！";
        }
        sendUiMessage(msg);
    }

    OnAliPayListener onAliPayListener = new OnAliPayListener() {

        @Override
        public void onSuccess() {
            Message msg = new Message();
            msg.what = MSG_ALIPAY_SUCCESS;
            sendUiMessage(msg);
        }

        @Override
        public void onFailed(String errorMsg, String statusCode) {
            Message msg = new Message();
            msg.what = MSG_ALIPAY_FAILED;
            Bundle bundle = new Bundle();
            bundle.putString("errorMsg", errorMsg);
            bundle.putString("statusCode", statusCode);
            msg.setData(bundle);
            sendUiMessage(msg);
        }
    };

    private int calcNeedMoney() {
        return (int) Math.ceil(mRechargeValue
                - UserManager.getInstance().getCurrentUserInternal().getKubiNum()
                / PayManager.getYoubiRatio()
                - ((mSelectedCoupon == null) ? 0 : mSelectedCoupon.getMoney()));
    }

    /**
     * 网银支付请求
     * 
     * @param carType "":表示银联卡; 01:表示借记卡; 02：表示信用卡
     */
    private void payByUnion(String carType) {
        int payValue = calcNeedMoney();

        UnionPayRequestParams requestParams = new UnionPayRequestParams();
        mOrderId = SDKControler.createNewOrderId();
        User user = UserManager.getInstance().getCurrentUserInternal();
        requestParams.setUserName(user.getAccountName());
        requestParams.setChargeType(ChargeType.TYPE_YIPAY);
        requestParams.setMoney(payValue * 100);
        requestParams.setDirectCharge(0);
        requestParams.setOutOrderId(mOrderId);
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());
        requestParams.setCardtype(carType);
        PayManager.payByUnion(this, CODE_START_ACTIVITY_REQUEST, requestParams);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        /*************************************************
         * 步骤3：处理银联手机支付控件返回的支付结果
         ************************************************/
        if (data == null || resultCode != Activity.RESULT_OK) {
            return;
        }

        sendEmptyUiMessage(MSG_STOP_LOADING);
        switch (requestCode) {
            case CODE_START_ACTIVITY_REQUEST: {
                /*
                 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
                 */
                int payResult = data.getExtras().getInt("pay_result", 0);
                String resultDescription = data.getStringExtra("result_description");
                switch (payResult) {
                    case 1:
                        // 支付成功
                        sendEmptyBackgroundMessage(MSG_REQUEST_PAY_STATUS);
                        break;
                    case 2:
                        // 支付失败
                        if (!TextUtils.isEmpty(resultDescription)) {
                            showNoticeDialog(resultDescription);
                        }
                        break;
                    case 3:
                        // 用户取消了支付
                        if (!TextUtils.isEmpty(resultDescription)) {
                            showNoticeDialog(resultDescription);
                        }
                        break;

                    default:
                        break;
                }
                break;

            }

            // 微信返回
            default:
                Message msg = Message.obtain();
                Bundle result = data.getExtras();
                String respCode = result.getString("resultCode");
                if (!TextUtils.isEmpty(respCode) && respCode.equalsIgnoreCase("success")) {
                    // 标示支付成功
                    sendEmptyBackgroundMessage(MSG_REQUEST_PAY_STATUS);
                } else { // 其他状态NOPAY状态：取消支付，未支付等状态
                    msg.what = MSG_REQUEST_FAILED;
                    msg.obj = "用户取消支付（" + respCode + ")";
                    sendUiMessage(msg);
                }

                break;
        }

    }

    private void payByWeixin() {
        BasePayRequestParams requestParams = new BasePayRequestParams();
        requestParams.setDirectCharge(0);
        User user = UserManager.getInstance().getCurrentUserInternal();
        requestParams.setUserName(user.getAccountName());
        requestParams.setChargeType(ChargeType.TYPE_WEIXIN);
        requestParams.setMoney(calcNeedMoney() * 100);
        requestParams.setOutOrderId(mOrderId);
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());

        WeiXinPayTask httpTask = new WeiXinPayTask();
        WeiXinPayHttpResponse response = httpTask.request(requestParams);
        Message msg = Message.obtain();
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                if ("1".equals(response.getResult_code())) {
                    msg.what = MSG_REQUEST_WEIXIN_INFO_SUCCESS;
                    msg.obj = response;
                } else {
                    msg.what = MSG_REQUEST_WEIXIN_INFO_FAILED;
                    msg.obj = response.getResult_msg();
                }
            } else {
                msg.what = MSG_REQUEST_WEIXIN_INFO_FAILED;
                msg.obj = response.getPrompt();
            }
        } else {
            msg.what = MSG_REQUEST_WEIXIN_INFO_FAILED;
            msg.obj = "网络异常，请检查网络连接！";
        }
        sendUiMessage(msg);
    }

    /**
     * 判断用户是否设置支付密码
     */
    private void checkPayPasswdState() {
        CheckPayPasswdStateTask task = new CheckPayPasswdStateTask();
        CheckPayPswStateResponse response = task.request(UserManager.getInstance()
                .getCurrentUserName());
        if (response != null) {
            if (response.isUseful() && response.isPayPasswdSeted() && !response.isLocked()) {
                sendEmptyUiMessage(MSG_REQUEST_PAY_STATUES_SUCCESS);
            } else if (response.isUseful() && !response.isPayPasswdSeted() && !response.isLocked()) {
                sendEmptyUiMessage(MSG_STOP_LOADING);
                sendEmptyBackgroundMessage(MSG_REQUEST_KUBI_PAY);
            } else {
                Message msg = Message.obtain();
                msg.what = MSG_REQUEST_FAILED;
                msg.obj = response.getPrompt();
                sendUiMessage(msg);
            }
        } else {
            Message msg = Message.obtain();
            msg.what = MSG_REQUEST_FAILED;
            msg.obj = "网络请求失败";
            sendUiMessage(msg);
        }

    }

    private void showInputPayPasswdDialog() {
        if (mInputPayPasswdDialog == null) {
            mInputPayPasswdDialog = new InputPayPasswdDialog(this);
        }

        mInputPayPasswdDialog.setPayInfo(AppUtil.getAppName(this),
                mRechargeValue * PayManager.getYoubiRatio() + "");
        mInputPayPasswdDialog.setOnPasswordChangedListener(new OnPasswordChangedListener() {
            @Override
            public void onMaxLength(String psw) {
                Message msg = Message.obtain();
                msg.what = MSG_REQUEST_KUBI_PAY;
                msg.obj = psw;
                sendBackgroundMessage(msg);
            }

            @Override
            public void onChanged(String psw) {
            }
        });
        mInputPayPasswdDialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface arg0) {
                mInputPayPasswdDialog.hideSoftInput();
                mInputPayPasswdDialog = null;
            }
        });

        mInputPayPasswdDialog.show();
    }

    /**
     * 游币支付请求
     */
    private void payByKubi(String passwd) {
        User user = UserManager.getInstance().getCurrentUserInternal();
        if (user == null) {
            return;
        }
        KubiPayRequestParams requestParams = new KubiPayRequestParams();
        // 兑换金额减去代金券金额
        requestParams.setMoney(mRechargeValue * PayManager.getYoubiRatio());
        requestParams.setUserName(user.getAccountName());
        requestParams.setOutOrderId(SDKControler.createNewOrderId());
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());
        requestParams.setKugouToken(user.getKugouToken());
        requestParams.setPayPasswd(passwd);
        requestParams.setCouponId(mSelectedCoupon != null ? mSelectedCoupon.getId() : 0);
        PayManager.payByKubi(requestParams, onKubiPayListener);
    }

    OnKubiPayListener onKubiPayListener = new OnKubiPayListener() {

        @Override
        public void onSuccess(String leftKubi) {
            Message msg = new Message();
            msg.what = MSG_KUBIPAY_SUCCESS;
            msg.obj = leftKubi;
            sendUiMessage(msg);
        }

        @Override
        public void onFailed(String errorMsg) {
            Message msg = new Message();
            msg.what = MSG_KUBIPAY_FAILED;
            msg.obj = errorMsg;
            sendUiMessage(msg);
        }
    };

    @Override
    protected void onBackBtnClick() {
        if (mRechargeSuccessLayout.getVisibility() == View.VISIBLE) {
            enterGame();
            finish();
        } else {
            super.onBackBtnClick();
        }
    }

    @Override
    public void onBackPressed() {
        if (mRechargeSuccessLayout.getVisibility() == View.VISIBLE) {
            enterGame();
            finish();
        } else {
            super.onBackPressed();
        }
    }

}
